//
//  radioController.m
//  Gegeda_music_MY
//
//  Created by lanou3g on 15/11/9.
//  Copyright © 2015年 周莹. All rights reserved.
//

#import "radioController.h"
#import "radioTableViewCell.h"
#import "radioModel.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "MBProgressHUD+MJ.h"
#import "RadioDetailViewController.h"
#import "songListModel.h"
#import "DetailTableViewCell.h"


#define Url @"http://mobile.ximalaya.com/mobile/discovery/v1/rankingList/album?device=android&key=ranking%3Aalbum%3Aplayed%3A7%3A17&pageId=1&pageSize=40"

#define url1 @"http://mobile.ximalaya.com/mobile/discovery/v1/rankingList/album?device=android&key=ranking%3Aalbum%3Aplayed%3A7%3A17&pageId="
#define url2 @"&pageSize=40"
@interface radioController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *radioTableView;

//解析数据
@property(nonatomic, strong)NSMutableArray *dataArray;
@end

@implementation radioController

#pragma mark - 懒加载
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)radioTableView{
    if (!_radioTableView) {
        _radioTableView = [[UITableView alloc] init];
    }
    return _radioTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [[UIColor alloc] initWithRed:255.0/255 green:222.0/255 blue:249.0/255 alpha:1.0];
    self.radioTableView.delegate = self;
    self.radioTableView.dataSource = self;
    [self downLoadGiftDataFinish:^{
        [self.radioTableView reloadData];
    } withIndex:self.index];
    
    //注册cell
    [self.radioTableView registerNib:[UINib nibWithNibName:@"radioTableViewCell" bundle:nil] forCellReuseIdentifier:@"tableViewCell"];
    //菊花
    [MBProgressHUD showMessage:@"正在加载,请稍等" toView:self.view];
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    
    [self.radioTableView addHeaderWithTarget:self action:@selector(headerHeightDidClicked)];
    [self.radioTableView headerBeginRefreshing];
    [self.radioTableView addFooterWithTarget:self action:@selector(footerefreshing)];
    
    self.radioTableView.headerPullToRefreshText = @"下拉可以刷新";
    self.radioTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.radioTableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    self.radioTableView.footerPullToRefreshText = @"- The End -";
    self.radioTableView.footerReleaseToRefreshText = @"已经到头了";
    self.radioTableView.footerRefreshingText = @"- The End -";
    
    
}


-(void)headerHeightDidClicked
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        if (self.dataArray == nil) {
            
            // 刷新表格
            [self.radioTableView reloadData];
            
        }
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.radioTableView headerEndRefreshing];
    });}

-(void)footerefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        [self downLoadGiftDataFinish:^{
            [self.radioTableView reloadData];
            
            self.index = (self.radioTableView.contentOffset.y - 1515) / 2000 ;
            
            self.index = self.index + 1;
            
        } withIndex:self.index];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.radioTableView footerEndRefreshing];
        
        
    });
    
}

#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
    //return 10;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    radioModel *model = self.dataArray[indexPath.row];
    static NSString *cell_id = @"tableViewCell";
    radioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id forIndexPath:indexPath];
    [cell setCellDataWithModel:model];
    UIColor *color  = [[UIColor alloc] initWithRed:255.0/255 green:222.0/255 blue:249.0/255 alpha:1.0];
    cell.backgroundColor = color;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    radioModel *model = self.dataArray[indexPath.row];
    RadioDetailViewController *radio = [[RadioDetailViewController alloc] init];
    [self.navigationController pushViewController:radio animated:YES];
    
    radio.albumId = model.albumId;
    radio.position = [NSString stringWithFormat:@"%ld",indexPath.row];
    
}


#pragma mark - 数据请求
-(void)downLoadGiftDataFinish:(void(^)())result withIndex:(NSInteger)index{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *url3 = [NSString stringWithFormat:@"%@%ld%@", url1, index + 1, url2];
        NSURL *url4 = [NSURL URLWithString:url3];
        NSURLRequest *request = [NSURLRequest requestWithURL:url4];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array =resultDict[@"list"];
            for (NSDictionary *dict in array) {
                radioModel *model = [[radioModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                result();
            });
            
        }];
        
    });
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
